package cn.wolfcode.wolf2w.redis.service.impl;

import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.redis.util.RedisKeys;
import cn.wolfcode.wolf2w.util.AssertUtil;

import cn.wolfcode.wolf2w.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
//@Transactional
public class UserInfoRedisService implements IUserInfoRedisService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public String setToken(UserInfo user) {
        //创建token
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        //获取key值
        String key = RedisKeys.USER_TOKEN.join(token);
        String value = JSON.toJSONString(user);
        //存储token,有效时间30分钟
        redisTemplate.opsForValue().set(key,value,RedisKeys.USER_TOKEN.getTime(), TimeUnit.SECONDS);
        return token;
    }

    /**
     * 根据token获取当前登录用户(userInfo对象)
     * @param token
     * @return
     */
    @Override
    public UserInfo getUserInfoByToken(String token) {
        //空值判断
        if (!StringUtils.hasLength(token)) {
            return null;
        }
        //获取key
        String key = RedisKeys.USER_TOKEN.join(token);
        //判断Redis数据库中是否有当前key
        if (redisTemplate.hasKey(key)) {
            String userInfo = redisTemplate.opsForValue().get(key);
            //在进行判断查询出来的字符串是否有值
            if (StringUtils.hasLength(userInfo)) {
                //将字符串转换成UserInfo对象
                UserInfo user= JSON.parseObject(userInfo, UserInfo.class);
                //重置时间
                redisTemplate.expire(key,RedisKeys.USER_TOKEN.getTime(),TimeUnit.SECONDS);
                return user;
            }
        }
        return null;
    }
}
